import React, { useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper, PageContainer } from '@ant-design/pro-layout';
import { Modal, message, Button, Card, Tabs, Table, Collapse, Form, Input, Tag, Empty, Space } from 'antd';
import { CopyOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import InfoTitle from '@/components/InfoShow/InfoTitle';
import CommonDescription from '@/components/InfoShow/CommenDescription';
import trans from '@/utils/translate';
import { getDetail, deleteNode, getServiceNodes, updateNode, getPredict } from './service';
import { connect, ConnectProps, Link, useIntl, history } from 'umi';
import byteToMb from '@/utils/byteToMb';
import format from '@/utils/format';
import { getStatus } from '../utils';
import { inference } from '../const';
import AdvancedConfiguration from './components/AdvanceConfiguration';
import { edgeRequest } from '@/utils/request';
import { model } from './components/SelectModel';
import CopyToClipboard from 'react-copy-to-clipboard';
import ATable, { ATableColumn, SearchToolBarProps } from '@apulis/table';
import type { ActionType } from '@apulis/table/lib/typing';
// import PortMapping from './components/PortMapping';

const { Panel } = Collapse;
const { Item } = Form;
interface ports {
  infer: object;
  others: object;
}
interface instance {
  id: number;
  orgId: number;
  groupId: number;
  userId: number;
  userName: string;
  serviceNodeId: string;
  nodeId: string;
  serviceId: string;
  status: string;
  createdAt: number;
  updatedAt: number;
}
interface info {
  caller: string;
  containerImage: string;
  containerImageTag: string;
  containerNetwork: string;
  containerPorts: ports;
  containerPrivilegeMode: false
  containerResart: string;
  containerRunCmd: string;
  containerRunParams: string;
  createdAt: number;
  describe: string;
  envs: string;
  groupId: number;
  id: number;
  models: model[];
  name: string;
  nodeIds: string[];
  orgId: number;
  serviceId: string;
  startTime: number;
  status: string;
  updatedAt: number;
  url: string;
  userId: number;
  userName: string;
}

interface Props extends ConnectProps {}
const Detail: React.FC<Props> = (props) => {
  const [basic, setBasic] = useState({});
  const [info, setInfo] = useState<info|{}>({});
  const [serviceId, setServiceId] = useState('');
  const [ports, setPorts] = useState<ports|{}>({});
  const [inputParams, setInputParams] = useState([]); // 输入参数
  const [outputParams, setOutputParams] = useState([]); // 输出参数

  const { formatMessage: f } = useIntl();
  const tableRef = useRef<ActionType>();
  const { TabPane } = Tabs;
  const changeTab = () => {};
  const { match } = props;
  const { id: nodeId } = match?.params as { id: string};
  const columnsInstance: ATableColumn[] = [
    {
      title: trans('nodeManagement.edgeNode.nodeName'),
      dataIndex: 'nodeName',
      render: (text: string, record: instance) =>
        <Link to={`/node-management/edge-node/node-detail/${record.nodeId}`}>{text}</Link>
    },
    {
      title: trans('deployOnline.edgeInference.instanceId'),
      dataIndex: 'serviceNodeId',
      render: (text: string) => {
        return (
          <span>
            {text}
            <CopyToClipboard
              text={text}
              onCopy={() => {
                message.info('复制成功');
              }}
            >
              <CopyOutlined style={{ cursor: 'pointer' }} />
            </CopyToClipboard>
          </span>
        )
      }
    },
    {
      title: trans('deployOnline.edgeInference.instanceStatus'),
      dataIndex: 'status',
      render: (text: string) => getStatus(text),
    },
    {
      title: trans('deployOnline.edgeInference.accessPath'),
      dataIndex: 'serviceName',
      render: (text: string) => {
        const txt = `http:<本机IP>:${ports[0]?.value}`;
        return (
          <span>
            {txt}
            <CopyToClipboard
              text={txt}
              onCopy={() => {
                message.info('复制成功');
              }}
            >
              <CopyOutlined style={{ cursor: 'pointer' }} />
            </CopyToClipboard>
          </span>
        )
      }
    },
    {
      title: trans('common.operation'),
      dataIndex: 'operation',
      render: (text: string, record: instance) =>
      {
        return (
          <Space>
            {record.status === 'stop' && (
              <a onClick={() => updateNodeype(record.serviceNodeId, 'start')}>
                {trans('deployOnline.centralInference.start')}
              </a>
            )}
            {(record.status === 'running' ||
              record.status === 'scheduling') && (
              <a onClick={() => updateNodeype(record.serviceNodeId, 'stop')}>
                {trans('deployOnline.centralInference.stop')}
              </a>
            )}
            {(
              record.status === 'error' ||
              record.status === 'stop' ||
              record.status === 'model-transform') && (
              <a style={{ color: 'red' }} onClick={() => handleDelete(record.serviceNodeId)}>
                {trans('common.delete')}
              </a>
            )}
          </Space>
        );
      }
    },
  ];

  const columnsParams = [
    { title: '名称', dataIndex: 'name' },
    { title: '类型', dataIndex: 'type' },
  ]

  const updateNodeype = async (id: string, cmd: string) => {
    const res = await updateNode(id, cmd)
    if (res && res.code == 0) {
          message.success('操作成功');
          tableRef.current?.reload();
        } else {
          message.error('操作失败');
        }
  }

  const handleDelete = (nodeId: string) => {
    return (
      Modal.confirm({
        centered: true,
        closable: true,
        icon: <ExclamationCircleOutlined />,
        maskClosable: true,
        okType: 'danger',
        okText: f({ id: 'operation.confirm' }),
        cancelText: f({ id: 'operation.cancel' }),
        width: '30%',
        title: <div style={{ fontWeight: 'bold' }}>
          {f({ id: 'operation.delete.confirm' })}
        </div>,
        content: <div>{f({ id: 'operation.delete.reconfirm' })}</div>,
        onOk: async () => {
          deleteNode(nodeId).then(res => {
            if (res && res.code === 0) {
              message.success(f({ id: 'operation.delete.success' }));
              tableRef.current?.reload();
            } else {
              message.error('未删除成功');
            }
          })
        },
        cancelButtonProps: {},
        onCancel: () => {},
      })
    )
  }

  const formatPorts = (ports: ports) => {
    console.log(ports);
    let portsTemp = [];
    const inferKey = Object.keys(ports.infer)[0];
    portsTemp.push({ key: inferKey, value: ports.infer[inferKey]});
    Object.entries(ports.others).forEach((key: string|number, value: string|number) => {
      portsTemp.push({key, value});
    });
    console.log(portsTemp);
    setPorts(portsTemp);
  }
  const columnsPorts = [
    {
      title: trans('deployOnline.edgeInference.add.containerPort'),
      dataIndex: 'key',
    },
    {
      title: trans('deployOnline.edgeInference.add.hostPort'),
      dataIndex: 'value',
    },
  ];

  const getRestart = (option: string) => {
    const starts = new Map([
      ['always', [
        trans('deployOnline.edgeInference.add.restartAlways'),
        trans('deployOnline.edgeInference.add.restartAlwaysTip')
      ]],
      ['on-failure', [
        trans('deployOnline.edgeInference.add.restartOnFailure'),
        trans('deployOnline.edgeInference.add.restartOnFailureTip')
      ]],
      ['no', [
        trans('deployOnline.edgeInference.add.noRestart'),
        trans('deployOnline.edgeInference.add.noRestartTip')
      ]],
    ]);
    return starts.get(option);
  }
  // 获取运行参数
  const getParams = (id: string) => {
    getPredict(id).then(res => {
      if (res && res.code === 0) {
        const { inputParams, outputParams } = res.data.center;
        setInputParams(inputParams);
        setOutputParams(outputParams);
        console.log(res.data);
      } else {
        message.error('获取参数失败')
      }
    })
  }

  useEffect(() => {
    getDetail(nodeId).then(res => {
      if (res && res.code === 0) {
        const { data } = res as { data: inference};
        console.log(data);
        // const { data } = res;
        setInfo(data);
        formatPorts(data.containerPorts);
        const {
          name,
          serviceId,
          status,
          describe,
          models,
          createdAt,
          startTime,
        } = data as {
          name: string,
          serviceId: string,
          status: string,
          describe: string,
          createdAt: number,
          startTime: number,
          models: model[],
        };
        setServiceId(serviceId);
        getParams(serviceId);
        console.log(models)
        const m: model = models[0];
        setBasic({
          serviceName: name,
          serviceId,
          // status: getStatus(status),
          describe,
          model: `${m.name}-${m.version}`,
          createdAt: format(createdAt),
          // startTime: format(createdAt), // 肖阳改为 createdAt
        });
      }
    })
  }, [])

  return (
    <PageContainer onBack={() => {
        history.push('/deploy-online/edge-inference');
    }}>
      <Card>
        <InfoTitle title='document.basic' />
        <CommonDescription obj={basic} prefix='deployOnline.edgeInference' />
      </Card>
      <Card>
        <Tabs defaultActiveKey='1' onChange={changeTab}>
          <TabPane tab={trans('deployOnline.edgeInference.instanceInfo')} key='1'>
            { serviceId &&
              <ATable
                actionRef={tableRef}
                rowKey='id'
                columns={columnsInstance}
                dataSourceAPIPath={`/inference/serviceNode/${serviceId}`}
                request={edgeRequest}
                reloadIcon={false}
              ></ATable>
            }
          </TabPane>
          <TabPane tab={trans('deployOnline.edgeInference.callGuide')} key='2'>
            <div className="api-info">
              <span>参数设置</span>
              <Collapse defaultActiveKey={1}>
                <Panel header={<><Tag color='#0D8C2B'>POST</Tag>/</>} key='1'>
                  输入参数
                  <Table columns={columnsParams} dataSource={inputParams} pagination={false}></Table>
                  <div style={{marginTop: '30px'}}>输出参数</div>
                  <Table columns={columnsParams} dataSource={outputParams} pagination={false}></Table>
                </Panel>
              </Collapse>
            </div>
          </TabPane>
          <TabPane tab={trans('deployOnline.edgeInference.accessConfiguration')} key='3'>
            <Item
              label={trans('deployOnline.edgeInference.add.portMapping')}
              labelAlign='left'
              required
              tooltip={trans('deployOnline.edgeInference.add.portMapping.tip')}
            >
              <Table columns={columnsPorts} dataSource={ports} pagination={false} key='key'></Table>
            </Item>
          </TabPane>
          <TabPane tab={trans('deployOnline.edgeInference.advancedConfiguration')} key='4'>
            <Collapse defaultActiveKey={['0']}>
              <Panel
                header={trans('deployOnline.edgeInference.add.runCmd')}
                key='1'
                extra={
                  <span style={{color:'#ccc',fontSize:'12px'}}>
                    {trans('deployOnline.edgeInference.add.runCmdAttention')}
                  </span>
                }
              >
                <Item label={trans('deployOnline.edgeInference.add.runCmd')}>
                  <Input readOnly value={(info as info).containerRunCmd}></Input>
                </Item>
                <Item label={trans('deployOnline.edgeInference.add.runParams')}>
                  <Input.TextArea readOnly value={(info as info).containerRunParams}></Input.TextArea>
                </Item>
              </Panel>
              <Panel header={trans('deployOnline.edgeInference.add.restartStrategy')} key='2'>
                <Item label={trans('deployOnline.edgeInference.add.restartStrategy')}>
                  <Button type='primary'>{getRestart((info as info).containerResart)?.[0]}</Button>
                  <p>{getRestart((info as info).containerResart)?.[1]}</p>
                </Item>
              </Panel>
            </Collapse>
            {/* <AdvancedConfiguration start={(info as inference).containerResart}></AdvancedConfiguration> */}
          </TabPane>
        </Tabs>
      </Card>
    </PageContainer>
  )
}

export default connect()(Detail);
